package com.honzh.work.controller;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.honzh.work.interceptor.BindInterceptor;
import com.honzh.work.interceptor.LoginInterceptor;
import com.honzh.work.model.Mail;
import com.honzh.work.model.Note;
import com.honzh.work.model.NoteWeek;
import com.honzh.work.model.User;
import com.honzh.work.model.UserMail;
import com.honzh.work.model.Weekend;
import com.honzh.work.utils.AESOperator;
import com.honzh.work.utils.DateUtil;
import com.honzh.work.utils.MD5Util;
import com.honzh.work.utils.MailSender;
import com.honzh.work.utils.PageUtil;
import com.honzh.work.utils.StrUtils;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.spring.Inject;
import com.jfinal.plugin.spring.IocInterceptor;

@Before(IocInterceptor.class)
public class AppController extends Controller {

	private static Logger logger = Logger.getLogger(AppController.class);

	public void index() {
		render("index.jsp");
	}

	/**
	 * 用户注册
	 * 
	 * @Title: register
	 * @author Realfighter void
	 * @throws
	 */
	public void register() {
		render("register.jsp");
	}

	/**
	 * 持久化注册信息
	 * 
	 * @Title: register2DB
	 * @author Realfighter void
	 * @throws
	 */
	public void register2DB() {
		boolean result = false;
		try {
			User user = getModel(User.class);
			user.set("pwd", MD5Util.md5(user.getStr("pwd")));
			user.set("userid", StrUtils.uuid());
			user.save();
			result = true;
		} catch (Exception e) {
			logger.error(e);
		}
		redirect("/result.honzh?result=" + result);
	}

	/**
	 * 跳转到结果页
	 * 
	 * @Title: result
	 * @author Realfighter void
	 * @throws
	 */
	public void result() {
		setAttr("result", getParaToBoolean("result"));
		render("result.jsp");
	}

	/**
	 * 登录表单提交
	 * 
	 * @Title: login
	 * @author Realfighter void
	 * @throws
	 */
	public void login() {
		User loginUser = getModel(User.class);
		String name = loginUser.getStr("name");
		String pwd = MD5Util.md5(loginUser.getStr("pwd"));
		// 根据用户名和密码查询用户
		User user = User.dao.findLoginUser(name, pwd);
		if (user != null) {
			setSessionAttr("honzh_user", user);
			redirect("/main.honzh");
		} else {
			redirect("/");
		}
	}

	/**
	 * 主页面
	 * 
	 * @Title: main
	 * @author Realfighter void
	 * @throws
	 */
	@Before(LoginInterceptor.class)
	public void main() {
		// 根据当前年月获取是否是休息日
		Weekend weekend = Weekend.dao.findFirst("select * from mst_weekend where year=? and month=?", DateUtil
				.getYear(), DateUtil.getMonth());
		if (weekend == null) {
			render("error.jsp");
		} else {
			String weekends = weekend.getStr("weekend");
			List<String> list = Splitter.on("#").splitToList(weekends);
			setAttr("weekend", list.contains(String.valueOf(DateUtil.getDay())));
			// 获取当前时间
			setAttr("date", DateUtil.getFull());
			int pagenum = 1;
			if (!isParaBlank(0)) {// 页码
				pagenum = getParaToInt(0);
			}
			// 获取所有的工作日志
			Page<Note> page = Note.dao.paginate(pagenum, 20, "select * ",
					" from mst_note where userid=? order by date desc", getUserid());
			setAttr("page", new PageUtil(page));
			render("main.jsp");
		}
	}

	/**
	 * 主页面2
	 * 
	 * @Title: mainweek
	 * @author Realfighter void
	 * @throws
	 */
	@Before(LoginInterceptor.class)
	public void mainweek() {
		// 根据当前年月获取是否是休息日
		Weekend weekend = Weekend.dao.findFirst("select * from mst_weekend where year=? and month=?", DateUtil
				.getYear(), DateUtil.getMonth());
		if (weekend == null) {
			render("error.jsp");
		} else {
			String weekends = weekend.getStr("weekend");
			List<String> list = Splitter.on("#").splitToList(weekends);
			setAttr("weekend", list.contains(String.valueOf(DateUtil.getDay())));
			// 获取当前时间
			setAttr("date", DateUtil.getFull());
			int pagenum = 1;
			if (!isParaBlank(0)) {// 页码
				pagenum = getParaToInt(0);
			}
			// 获取所有的周总结
			Page<NoteWeek> page = NoteWeek.dao.paginate(pagenum, 20, "select * ",
					" from mst_note_week where userid=? order by month desc,week desc", getUserid());
			setAttr("page", new PageUtil(page));
			render("main2.jsp");
		}
	}

	/**
	 * 日志填写页面
	 * 
	 * @Title: toNote
	 * @author Realfighter void
	 * @throws
	 */
	@Before(LoginInterceptor.class)
	public void toNote() {
		// 获取本月所有的周计划
		List<NoteWeek> noteWeeks = NoteWeek.dao.find(
				"select * from mst_note_week where month=? and userid=? order by month desc,week desc", getMonth(),
				getUserid());
		setAttr("noteWeeks", noteWeeks);
		setAttr("month", getMonth());
		// 设置日历显示min和max
		setAttr("min", DateUtil.getDay() - 1);
		setAttr("max", DateUtil.getLastDay() - DateUtil.getDay());
		render("note.jsp");
	}

	/**
	 * 周计划填写页面
	 * 
	 * @Title: toWeekend
	 * @author Realfighter void
	 * @throws
	 */
	@Before(LoginInterceptor.class)
	public void toWeekend() {
		setAttr("month", getMonth());
		render("noteweek.jsp");
	}

	/**
	 * 日志填写保存
	 * 
	 * @Title: note
	 * @author Realfighter void
	 * @throws
	 */
	@Before( { LoginInterceptor.class, Tx.class })
	public void note() {
		Note note = getModel(Note.class, "note");
		Note old = Note.dao.findFirst("select * from mst_note where date=? and userid=?", note.getStr("date"),
				getUserid());
		if (old != null) {
			old.delete();
		}
		note.set("userid", getUserid());
		note.save();
		redirect("/main.honzh");
	}

	/**
	 * 周总结填写保存
	 * 
	 * @Title: noteweek
	 * @author Realfighter void
	 * @throws
	 */
	@Before( { LoginInterceptor.class, Tx.class })
	public void noteweek() {
		NoteWeek note = getModel(NoteWeek.class, "noteweek");
		NoteWeek old = NoteWeek.dao.findFirst("select * from mst_note_week where week=? and month=? and userid=?", note
				.getInt("week"), getMonth(), getUserid());
		if (old != null) {
			note.set("weekid", old.getStr("weekid"));
			old.delete();
		} else {
			note.set("weekid", StrUtils.uuid());
		}
		note.set("userid", getUserid());
		note.set("month", getMonth());
		note.save();
		redirect("/mainweek.honzh");
	}

	/**
	 * 周总结更新保存
	 * 
	 * @Title: noteweek
	 * @author Realfighter void
	 * @throws
	 */
	@Before(LoginInterceptor.class)
	public void updateNoteWeek() {
		NoteWeek note = getModel(NoteWeek.class, "noteweek");
		note.update();
		redirect("/mainweek.honzh");
	}

	/**
	 * 工作日志更新保存
	 * 
	 * @Title: noteweek
	 * @author Realfighter void
	 * @throws
	 */
	@Before(LoginInterceptor.class)
	public void updateNote() {
		Note note = getModel(Note.class, "note");
		note.update();
		redirect("/main.honzh");
	}

	/**
	 * 绑定企业邮箱
	 * 
	 * @Title: toBindEmail
	 * @author Realfighter void
	 * @throws
	 */
	@Before(LoginInterceptor.class)
	public void toBindEmail() {
		// 获取当前用户绑定的邮箱
		UserMail userMail = UserMail.dao.findFirst("select * from sys_usermail where userid=?", getUserid());
		if (userMail != null) {
			// 密码解密
			userMail.set("password", AESOperator.INSTANCE.decrypt(userMail.getStr("password")));
		}
		setAttr("userMail", userMail);
		render("bindemail.jsp");
	}

	/**
	 * 绑定邮箱更新保存
	 */
	@Before( { LoginInterceptor.class, Tx.class })
	public void bindEmail() {
		UserMail mail = getModel(UserMail.class, "usermail");
		UserMail old = UserMail.dao.findFirst("select * from sys_usermail where userid=?", getUserid());
		if (old != null) {
			old.delete();
		}
		mail.set("password", AESOperator.INSTANCE.encrypt(mail.getStr("password")));
		mail.set("userid", getUserid());
		mail.save();
		redirect("/toBindEmail.honzh");
	}

	@Inject.BY_NAME
	private JavaMailSenderImpl mailSender;// spring配置中定义

	/**
	 * 发送日志邮件
	 */
	@Before( { LoginInterceptor.class, BindInterceptor.class })
	public void sendNoteEmail() {
		Integer noteid = getParaToInt(0);
		// 根据noteid获取当前日志和周报
		Note note = Note.dao.findById(noteid);
		NoteWeek noteWeek = NoteWeek.dao.findFirst("select * from mst_note_week where weekid=? and userid=?", note
				.getStr("weekid"), getUserid());
		// 获取用户绑定的邮箱信息
		UserMail userMail = UserMail.dao.findFirst("select * from sys_usermail where userid=?", getUserid());
		MailSender sender = new MailSender(mailSender);
		sender.setFrom(userMail.getStr("email"));// 发件人
		sender.setTo(userMail.getStr("receiver"));// 收件人
		sender.setPassword(AESOperator.INSTANCE.decrypt(userMail.getStr("password")));// 密码
		String title = getUser().getStr("realname") + "【" + note.getStr("date") + "】" + "工作日志";
		sender.setSubject(title);// 设置主题
		sender.setTemplateName("mynote.html");// 设置的邮件模板
		Map<String, String> params = Maps.newHashMap();
		params.put("userid", getUserid());
		params.put("title", title);
		List<Note> notes = Lists.newArrayList(note);
		// 设置模板中的参数
		sender.sendWithHtmlTemplate(params, notes, noteWeek);
		// 跳转到邮件发送结果列表
		redirect("/mails.honzh");
	}

	/**
	 * 发送周报邮件
	 */
	@Before( { LoginInterceptor.class, BindInterceptor.class })
	public void sendWeekEmail() {

		String weekid = getPara(0);
		// 根据weekid获取周报和所有当周日志
		NoteWeek noteWeek = NoteWeek.dao.findFirst("select * from mst_note_week where weekid=? and userid=?", weekid,
				getUserid());
		List<Note> notes = Note.dao.find("select * from mst_note where weekid = ? and userid=? order by date desc",
				weekid, getUserid());
		// 获取用户绑定的邮箱信息
		UserMail userMail = UserMail.dao.findFirst("select * from sys_usermail where userid=?", getUserid());
		MailSender sender = new MailSender(mailSender);
		sender.setFrom(userMail.getStr("email"));// 发件人
		sender.setTo(userMail.getStr("receiver"));// 收件人
		sender.setPassword(AESOperator.INSTANCE.decrypt(userMail.getStr("password")));// 密码
		String title = getUser().getStr("realname") + "【" + noteWeek.getStr("month") + "第" + noteWeek.getInt("week")
				+ "周】" + "周报";
		sender.setSubject(title);// 设置主题
		sender.setTemplateName("mynote.html");// 设置的邮件模板
		Map<String, String> model = Maps.newHashMap();
		model.put("userid", getUserid());
		model.put("title", title);
		// 设置模板中的参数
		sender.sendWithHtmlTemplate(model, notes, noteWeek);
		// 跳转到邮件发送结果列表
		redirect("/mails.honzh");
	}

	/**
	 * 邮件发送记录
	 */
	@Before(LoginInterceptor.class)
	public void mails() {
		// 根据当前年月获取是否是休息日
		Weekend weekend = Weekend.dao.findFirst("select * from mst_weekend where year=? and month=?", DateUtil
				.getYear(), DateUtil.getMonth());
		if (weekend == null) {
			render("error.jsp");
		} else {
			String weekends = weekend.getStr("weekend");
			List<String> list = Splitter.on("#").splitToList(weekends);
			setAttr("weekend", list.contains(String.valueOf(DateUtil.getDay())));
			// 获取当前时间
			setAttr("date", DateUtil.getFull());
			int pagenum = 1;
			if (!isParaBlank(0)) {// 页码
				pagenum = getParaToInt(0);
			}
			// 获取所有的周总结
			Page<Mail> page = Mail.dao.paginate(pagenum, 20, "select * ",
					" from sys_mail where userid=? order by createtime desc", getUserid());
			setAttr("page", new PageUtil(page));
			render("mails.jsp");
		}
	}

	private User getUser() {
		return getSessionAttr("honzh_user");
	}

	private String getUserid() {
		return getUser().getStr("userid");
	}

	private String getMonth() {
		return DateUtil.getWeekMonth();
	}

}
